<template>
	<div>
		<img :id="imgId" />
		<w-link v-if="showDelete" type="danger" @click="onDelete">删除</w-link>
		<w-link v-if="showDownload" type="primary" class="btn-download" size="mini" href="">下载</w-link>
	</div>
</template>
<script>
/**
 * Barcode by shang 2020/9/23
 * @desc Barcode 条码
 * @code [String] type 条码
 * @showCode [Boolean] type 显示条码文字
 * @showDownload [Boolean] type 显示下载 按钮
 * @showDelete [Boolean] type 显示删除 按钮
 */
import JsBarcode from 'jsbarcode'
export default {
	name: 'barcode',
	props: {
		code: String,
		showCode: Boolean,
		showDownload: Boolean,
		showDelete: Boolean
	},
	data () {
		return {
			imgId: this.$fxUtils.createUUID()
		}
	},
	watch: {
		code: {
			immediate: true,
			handler (val) {
				this.$nextTick(() => {
					JsBarcode(`#${this.imgId}`, this.code, {
						format: 'CODE39',
						lineColor: '#000',
						background: '#EBEEF5',
						width: 1,
						height: 40,
						displayValue: this.showCode
					})

					if (this.showDownload) {
						const imgSrc = this.$el.querySelector('img').src
						this.$el.querySelector('.btn-download').href = imgSrc
						this.$el.querySelector('.btn-download').download = 'barcode-' + this.code
					}
				})
			}
		}
	},
	methods: {
		onDelete () {
			this.$emit('on-delete-barcode', this.code)
		}
	}
}
</script>
<style lang="stylus" scoped>
</style>
